using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using Jungle.Code.Utils;

namespace Jungle.HttpModules
{
	public class UrlHandlerModule : IHttpModule
	{
		// Constructors
		public UrlHandlerModule() {
		}


		// Methods
		public void Init(HttpApplication context) {
			context.BeginRequest += new EventHandler(this.context_BeginRequest);
			context.EndRequest += new EventHandler(this.context_EndRequest);
		}

		public void Dispose() {
		}

		private void RewriteUrl(string urlToRewrite, HttpContext context) {
			NameValueCollection collection1 = (NameValueCollection)ConfigurationSettings.GetConfig("UrlMappings");
			for (int index = 0; index < collection1.Count; index++) {
				string text1 = UrlHelper.GetApplicationPath() + collection1.GetKey(index);
				Regex regex1 = new Regex(text1, RegexOptions.CultureInvariant | (RegexOptions.Singleline | (RegexOptions.Compiled | RegexOptions.IgnoreCase)));
				if (regex1.IsMatch(urlToRewrite)) {
					if (collection1[index] != string.Empty) {
						if (Convert.ToBoolean(HttpContext.Current.Application["IsUpgrading"])) {
							HttpContext.Current.Response.Redirect("~/Sorry.aspx", true);
							return;
						}
						string text2 = regex1.Replace(urlToRewrite, UrlHelper.GetApplicationPath() + collection1[index]);
						string queryString = string.Empty;
						string pathInfo = string.Empty;
						string filePath = string.Empty;
						int length = text2.IndexOf("?");
						if ((length != -1) || ((length + 1) < text2.Length)) {
							queryString = text2.Substring(length + 1);
							text2 = text2.Substring(0, length);
						}
						int startIndex = text2.IndexOf("aspx/") + 4;
						if (startIndex > 3) {
							pathInfo = text2.Substring(startIndex);
							text2 = text2.Substring(0, startIndex);
						}
						filePath = text2;
						context.RewritePath(filePath, pathInfo, queryString);
					}
					break;
				}
			}
			context.Items["VirtualUrl"] = urlToRewrite;
		}

		private void context_BeginRequest(object sender, EventArgs e) {
			HttpApplication application1 = (HttpApplication)sender;
			application1.Context.Items["startTime"] = DateTime.Now;
			string urlToRewrite = HttpContext.Current.Request.RawUrl;
			this.RewriteUrl(urlToRewrite, application1.Context);
		}

		private void context_EndRequest(object sender, EventArgs e) {
			HttpApplication application1 = (HttpApplication)sender;
		}

	}
}
